package com.atguigu.filter;

import com.atguigu.util.JDBCUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1获取数据库连接
        Connection connection = JDBCUtils.getConnection();
        //2.将事物设为手动提交
       try{
           connection.setAutoCommit(false);
           //3放行
           chain.doFilter(req, resp);
           //4提交
           connection.commit();
       }catch (SQLException e) {
           e.printStackTrace();
           //回滚
           try {
               connection.rollback();
           } catch (SQLException ex) {
               ex.printStackTrace();
           }
       }finally {
           JDBCUtils.releaseConnection();
           //关闭资源
       }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
